package sort.impl;

import anaydis.sort.Sorter;
import anaydis.sort.SorterType;
import anaydis.sort.gui.ObservableSorter;
import anaydis.sort.gui.SorterListener;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public abstract class AbstractSorter implements Sorter, ObservableSorter {
    private SorterType type;
    protected List<SorterListener> sorterListeners;

    protected AbstractSorter(SorterType type){
        this.type = type;
        sorterListeners = new ArrayList<SorterListener>();
    }

    protected <T> boolean greater(Comparator<T> c, List<T> list,int i, int j){
        for (SorterListener sorterListener : sorterListeners) {
            sorterListener.greater(i, j);
        }
        return c.compare(list.get(i),list.get(j))>0;
    }

    protected <T> boolean equals(Comparator<T> c, List<T> list,int i, int j){
        for (SorterListener sorterListener : sorterListeners) {
            sorterListener.equals(i, j);
        }
        return c.compare(list.get(i),list.get(j))==0;
    }

    protected <T> void swap(List<T> list,int i, int j){
        T t = list.get(i);
        list.add(i,list.get(j));
        list.remove(i+1);
        list.add(j, t);
        list.remove(j+1);
        for (SorterListener sorterListener : sorterListeners) {
            sorterListener.swap(i, j);
        }
    }

    public SorterType getType(){
        return type;
    }

    public void addSorterListener(@org.jetbrains.annotations.NotNull anaydis.sort.gui.SorterListener sorterListener){
        sorterListeners.add(sorterListener);
    }

    public void removeSorterListener(@org.jetbrains.annotations.NotNull anaydis.sort.gui.SorterListener sorterListener){
        sorterListeners.remove(sorterListener);
    }
}
